import { useMemo } from 'react'
import { useMemoizedFn } from 'ahooks'
import { StatusPanelDef } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { IWaybillRecordItem, IWaybillRecordItemWithIndex } from '../../interface'
import { useBoundStore } from '../../store'
import { columnDefsConfig, defaultColDefConfig, selectionColumnDefConfig } from './List.config'

export const CusAgGridTable = () => {
  const gridRef = useBoundStore(store => store.gridRef)
  const loading = useBoundStore(store => store.request?.loading)
  const data = useBoundStore(store => store.request?.data)
  const page = useBoundStore(store => store.reqData?.page)
  const size = useBoundStore(store => store.reqData?.size)
  const setReqData = useBoundStore(store => store.setReqData)
  const getData = useBoundStore(store => store.getData)
  const setSelectedKeys = useBoundStore(store => store.setSelectedKeys)
  const selectedKeys = useBoundStore(store => store.selectedKeys)
  const setWaybillList = useBoundStore(store => store.setWaybillList)

  // 勾选统计 & 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    const statusPanels: StatusPanelDef[] = [
      {
        statusPanel: () => (
          <div style={{ marginTop: 12 }}>
            已选中 <b>{selectedKeys.length}</b> 条
          </div>
        ),
        align: 'left',
      },
    ]
    statusPanels.push({
      statusPanel: UnifiedPagination,
      statusPanelParams: UnifiedPagination.defineProps({
        current: page,
        pageSize: size,
        total: data?.total,
        onChange: (page, size) => {
          setReqData({ page, size })
          getData(true)
        },
      }),
    })
    return { statusPanels }
  }, [selectedKeys, page, size, data?.total])

  const columnDefs = useMemo(() => columnDefsConfig, [])

  const rowSelection = useMemo<ICusAgGridProps<IWaybillRecordItemWithIndex>['rowSelection']>(() => {
    return { mode: 'multiRow' }
  }, [])

  const onRowSelected = useMemoizedFn<NonNullable<ICusAgGridProps<IWaybillRecordItemWithIndex>['onRowSelected']>>(
    () => {
      const rows = gridRef.current?.api.getSelectedRows()
      if (rows) {
        setSelectedKeys(rows.map(r => r.waybillNo as string))
        setWaybillList(rows)
      }
    },
  )

  return (
    <CusAgGrid<IWaybillRecordItemWithIndex>
      ref={gridRef}
      loading={loading}
      rowData={data?.records as IWaybillRecordItem[] | undefined}
      columnDefs={columnDefs}
      defaultColDef={defaultColDefConfig}
      statusBar={statusBar}
      rowSelection={rowSelection}
      onRowSelected={onRowSelected}
      selectionColumnDef={selectionColumnDefConfig}
    />
  )
}
